#Author：雨霁夜茶

import requests
import json
import re
import time
import threading


data_value=0
data_dict={}
keys=set()
lock = threading.RLock()

def getdata():
    return data_dict

def load_data():
    try:
        res = requests.get("https://api.bitfinex.com/v2/tickers?symbols=ALL&_=1527751549684")
        text=res.text.replace("\"","\'")

        lock.acquire()

        text = json.loads(res.text)
        count = len(text)
        btc_price=0

        for i in range(count):
            key_1=text[i][0].replace('t','')
            data_value = float(text[i][1])
            if 'USD' in key_1:
                key = key_1.replace('USD','').lower()
                if key == 'btc':
                    keys.add(key)
                    data_dict[key] = {'usdt': data_value, 'btc': 1, 'precent': 0}
                    btc_price = data_value
                    break

        for i in range(count):
            key_1 = text[i][0].replace('t', '')
            data_value = float(text[i][1])
            if 'USD' in key_1:
                key = key_1.replace('USD', '').lower()
                keys.add(key)
                data_dict[key] = {'usdt': data_value, 'btc': 1, 'precent': 0}

        for i in range(count):
            key_1 = text[i][0].replace('t', '')
            data_value = float(text[i][1])
            if 'BTC' in key_1 and "USD" is not key_1:
                key = key_1.replace('BTC', '').lower()
                if key=='usd' or key=='eur' or key=='jpy' or key=='gbp':
                    continue
                keys.add(key)
                if data_dict.get(key) != None:
                    data_dict.get(key)['btc'] = data_value
                else:
                    data_dict[key] = {'key': key, 'usdt': data_value * btc_price, 'btc': data_value,
                                              'precent': 0}
        data_dict['btc']['btc']=1
        lock.release()
        print('下载成功：bitfinex')
        return data_dict, keys
    except requests.exceptions.RequestException:
        print('RequestException bitfinex')
        return data_dict, keys
    except requests.exceptions.ConnectionError:
        print('ConnectionError bitfinex')
        return data_dict, keys
    except Exception as e:
        print('Error bitfinex:',e)
        return data_dict, keys



def loadingdata():
    t1 = threading.Thread(target=load_data)
    t1.start()

if __name__ == "__main__":
    while True:
        loadingdata()
        time.sleep(2)
        # for k,v in data_dict.items():
        #     print(k,':',v)